package com.查找字符串;

/**
 * Sunday算法
 */
public class SundayTest {

    public static int containers(char[] sonArr, char c) {
        for (int i = sonArr.length - 1; i >= 0;
             i--) {
            if (sonArr[i] == c) {
                return sonArr.length - 1 - i;
            }
        }
        return -1;
    }


    public static int search(String father, String son) {
        char[] faterChars = father.toCharArray();
        char[] sonArray = son.toCharArray();

        int sonLength = sonArray.length;

        int farLength = faterChars.length;

        int i = 0, j = 0;

        while (i <= farLength - sonLength + j) {
            if (faterChars[i] != sonArray[j]) {
                if (i - j + sonLength == farLength) {
                    return -1;
                }
                // 主串中参加匹配的最末位字符的下一位字符，是否出现中子串中
                int pos = containers(sonArray, faterChars[i - j + sonLength]);
                if (pos == -1) {
                    i = i - j + sonLength;
                    j = 0;
                } else {
                    i = pos + 1;
                    j = 0;
                }
            } else {
                // 这是说明已经子串已经匹配到最后一个了
                if (j == sonLength - 1) {
                    return i - j;
                } else {
                    i++;
                    j++;
                }
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        System.out.print(search("babcd","abc"));
    }

}
